package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.article.ApArticleConfigMapper;
import com.heima.article.service.ApArticleService;
import com.heima.common.freemarker.FreemarkerGenerator;
import com.heima.file.MinIoTemplate;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private FreemarkerGenerator freemarkerGenerator;

    @Autowired
    private MinIoTemplate minIoTemplate;

    @Override
    public ResponseResult load(String loadType, ArticleHomeDto articleHomeDto) {

        List<ApArticle> apArticles = apArticleMapper.loadArticleList(articleHomeDto, loadType);
        return ResponseResult.okResult(apArticles);
    }

    //生成页面详情
    @Override
    @Async      //生成页面也会耗时，所以选择异步方式
    public void generate(Long articleId) {
        //查询article_content表获取content数据
        LambdaQueryWrapper<ApArticleContent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApArticleContent::getArticleId, articleId);
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(wrapper);
        if (apArticleContent == null) {
            log.warn("文章内容不存在");   //如果不存在直接返回
            return;
        }
        //创建map集合把上一步content数据赋值到content字段上
        String content = apArticleContent.getContent();
        Map<String, Object> params = new HashMap<>(1);
        params.put("content", JSONArray.parseArray(content));
        //调用freemarker插件，生成html文件
        InputStream generate = freemarkerGenerator.generate("article.ftl", params);
        //调用minio上传到minio
        String s = minIoTemplate.uploadFile("", "content1", generate, "html");
        //更新article表static_url字段
        ApArticle apArticle = apArticleMapper.selectById(articleId);
        if (apArticle == null) {
            log.warn("文章为空");
            return;
        }
        apArticle.setStaticUrl(s);
        apArticleMapper.updateById(apArticle);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ResponseResult saveArticle(ArticleDto dto) {
        //1.判空
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //先复制属性
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);
        //判断是新增还是修改
        Long id = dto.getId();
        if (id == null) {
            //2.新增流程
            //2.1 添加article表
            int insert = apArticleMapper.insert(apArticle);
            if (insert < 1) {
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
            }
            //2.2添加article_config表
            ApArticleConfig apArticleConfig = new ApArticleConfig();
            //填充字段
            apArticleConfig.setArticleId(apArticle.getId());
            apArticleConfig.setIsComment(true);
            apArticleConfig.setIsDelete(false);
            apArticleConfig.setIsDown(false);
            apArticleConfig.setIsForward(true);
            int insert1 = apArticleConfigMapper.insert(apArticleConfig);
            if (insert1 < 1) {
                throw new RuntimeException("配置表插入失败");
            }
            //5.添加article_content表
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            int insert2 = apArticleContentMapper.insert(apArticleContent);
            if (insert2 < 1) {
                throw new RuntimeException("内容表插入失败");
            }
            //调用详情生成
            generate(apArticle.getId());
            return ResponseResult.okResult(apArticle.getId());
        } else {
            //3.修改article  修改article_content
            //修改article
            int update = apArticleMapper.updateById(apArticle);
            if (update < 1) {
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
            }
            //修改article_content
            LambdaQueryWrapper<ApArticleContent> wrapper = new LambdaQueryWrapper<>();
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setContent(dto.getContent());
            wrapper.eq(ApArticleContent::getArticleId, id);
            int update1 = apArticleContentMapper.update(apArticleContent, wrapper);
            if (update1 < 1) {
                throw new RuntimeException("内容表修改失败");
            }
            generate(id);
            return ResponseResult.okResult(id);
        }

        //todo 注意每一个方法的作用，判断返回值是否正确
        // 这个地方与问题，应该把这个东西弄到判断里面去，新增和修改 最终返回的articleId方式是不一样的
        // 你可以看看笔记这个位置
//        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
